﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Helper;
using System.Configuration;
using StoreTransport.Business.Constants;

namespace StoreTransport.Presentation.Forms {
    public partial class ConfigurationForm : Form {
        public ConfigurationForm() {
            InitializeComponent();
        }

        private void _btxBrowseFile_Click(object sender, EventArgs e) {
            var FD = new System.Windows.Forms.OpenFileDialog();
            if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                _tbxImportFilePath.Text = FD.FileName;
            }
        }

        private void _btxImportData_Click(object sender, EventArgs e) {
            string DBExtendtionFile = ".mdf";
            string errorMessage = CommonHelper.CheckRequiredField(_tbxImportFilePath.Text, _lblImportFilePath.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            if (!(_tbxImportFilePath.Text.ToLower().EndsWith(DBExtendtionFile.ToLower()))) {
                errorMessage = Resources.StoreTransportResource.ErrorMessage_FilePathNotValid;
                MessageBox.Show(errorMessage);
                return;
            }
            
            // get the config file for this application
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // set the new values
            config.ConnectionStrings.ConnectionStrings[CommonConstant.ConnectionStringKey].ConnectionString = string.
                    Format(CommonConstant.ConnectionStringParten, _tbxImportFilePath.Text);

            // save and refresh the config file
            config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection(CommonConstant.ConnectionStringKey);
            MessageBox.Show(Resources.StoreTransportResource.Message_UpdateConfigurationSuccess);
            _tbxImportFilePath.Text = string.Empty;
            CommonHelper.OpenForm(this, new LoginForm());
        }

        private void ConfigurationForm_Load(object sender, EventArgs e) {
            _btxBrowseFile.Select();
            string connectionString = ConfigurationManager.ConnectionStrings[CommonConstant.ConnectionStringKey].ConnectionString;
            connectionString = connectionString.Replace(CommonConstant.ConnectionStringPrefix, string.Empty);
            connectionString = connectionString.Replace(CommonConstant.ConnectionStringSubFix, string.Empty);
            _tbxImportFilePath.Text = connectionString;
        }
    }
}
